package com.example.zwh.androidtaketest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.ResultSet;

import sqlOperate.JdbcDriver;
import sqlOperate.MySqlAction;
import java.sql.SQLException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button loginBtn;
    private Button registerBtn;
    private EditText acountET;
    private EditText passwardET;

//    private String username = null;
//    private String password = null;
    private JdbcDriver jdbcD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        init();
        initEvent();
    }

    public void init() {
        jdbcD = new JdbcDriver();

        loginBtn = findViewById(R.id.login);
        registerBtn = findViewById(R.id.register);

        acountET = findViewById(R.id.acount);
        passwardET = findViewById(R.id.passward);

    }

    public void initEvent() {
        loginBtn.setOnClickListener(this);
    }

    public void judgeLogin() {
        String acountTV = acountET.getText().toString();//获取账号
        String passwardTV = passwardET.getText().toString();//获取密码

        int judge = 1;

        if (jdbcD.getConn() == null) jdbcD.Driver();

        String sql = "select * from users";
        MySqlAction msa = new MySqlAction(sql, jdbcD.getConn());
        ResultSet rs = null;

        try {
            //提交
            rs = msa.getPst().executeQuery();
            while(rs.next()) {
                if (rs.getObject(2).equals(acountTV)) {
                    if (rs.getObject(3).equals(passwardTV)) {
                        System.out.println(rs.getObject(2).toString() + " " + rs.getObject(3).toString());

                        judge = 0;
                    }else {
                        //密码错误
                        System.out.println("passward error");
                        judge = 0;
                    }
                    break;
                }
            }if (judge == 1) {
                System.out.println("account error");
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                //连网必须不能在主线程连执行是数据库也是
                (new Thread(new Runnable() {
                    @Override
                    public void run() {
                        judgeLogin();
                    }
                })).start();
                break;
            default:
                break;
        }
    }
}
